import type { Next, Context } from 'koa';
import knex from '../utils/knex';
import { makeTree } from '../utils/tree';
import { dataScopeHandler } from '../services/auth';

/**
 * @api {get} /org/retrieve 查询部门(分页)
 * @apiVersion 1.0.0
 * @apiDescription create by wuyanshen
 * @apiName retrieve
 * @apiGroup 部门管理
 *
 * @apiParam {int} name 部门名称【必填】
 * @apiParam {String} status 部门状态 (0:正常 1:停用)【必填】
 *
 * @apiUse RequestHeader
 * @apiUse orgRetrieveSuccess
 * @apiUse RequestError
 */
async function retrieveAction(ctx: Context, next: Next) {
    const { name = '', status } = ctx.query;
    const whereObj: Record<string, any> = {};
    if (name) {
        whereObj.name = ['like', `%${name}%`];
    }
    if (status) {
        whereObj.status = status;
    }
    try {
        const res = await knex('sys_org').where(whereObj).orderByRaw('sort_num ASC').select();
        // 生成树形结构
        const tree = makeTree(res, 'id', 'pid', 'children');
        ctx.success(tree, '查询成功');
    } catch (e) {
        ctx.fail(500, '查询失败  ' + e);
    }
    return next();
}

/**
 * @api {get} /org/tree 查询部门(无数据权限)
 * @apiVersion 1.0.0
 * @apiDescription create by wuyanshen ->（角色管理-数据权限）
 * @apiName tree
 * @apiGroup 部门管理
 *
 * @apiUse RequestHeader
 * @apiUse orgTreeSuccess
 * @apiUse RequestError
 */
async function treeAction(ctx: Context, next: Next) {
    try {
        const res = await knex('sys_org').where({ status: '0' }).orderByRaw('sort_num ASC').select();
        // 生成树形结构
        const tree = makeTree(res, 'id', 'pid', 'children');
        ctx.success(tree, '查询成功');
    } catch (e) {
        ctx.fail(500, '查询失败 ' + e);
    }
    return next();
}

/**
 * @api {get} /org/treeScope 查询部门(数据权限)
 * @apiVersion 1.0.0
 * @apiDescription create by wuyanshen (带数据权限过滤)
 * @apiName treeScope
 * @apiGroup 部门管理
 *
 * @apiUse RequestHeader
 * @apiUse orgTreeScopeSuccess
 * @apiUse RequestError
 */
async function treeScopeAction(ctx: Context, next: Next) {
    try {
        const dataScopeSql = await dataScopeHandler(ctx.user.id);
        const res = await knex({ o: 'sys_org' }).where({ status: '0' }).whereRaw(dataScopeSql).orderByRaw('sort_num ASC').select();
        // 生成树形结构
        const tree = makeTree(res, 'id', 'pid', 'children');
        ctx.success(tree, '查询成功');
    } catch (e) {
        ctx.fail(500, '查询失败  ' + e);
    }
    return next();
}

/**
 * @api {post} /org/add 新增部门
 * @apiVersion 1.0.0
 * @apiDescription create by wuyanshen
 * @apiName add
 * @apiGroup 部门管理
 *
 * @apiParam {String}  name 部门名称【必填】
 * @apiParam {int}     pid 父级部门id【必填】
 * @apiParam {String}  address 地址【必填】
 * @apiParam {String}  phone 电话【必填】
 * @apiParam {int}     sortNum 排序【必填】
 * @apiParam {int}     status 部门状态 (0:正常 1:停用)【必填】
 *
 * @apiUse RequestHeader
 * @apiUse updateSuccess
 * @apiUse RequestError
 */
async function addAction(ctx: Context, next: Next) {
    const { name = '', pid, address = '', phone = '', sortNum, status } = ctx.request.body;
    try {
        await knex('sys_org').insert({
            name: name,
            pid: pid,
            address: address,
            phone: phone,
            sort_num: sortNum,
            status: status,
        });
        ctx.success('', '新增成功');
    } catch (e) {
        ctx.fail(500, '新增失败  ' + e);
    }
    return next();
}

/**
 * @api {put} /org/update 修改部门
 * @apiVersion 1.0.0
 * @apiDescription create by wuyanshen
 * @apiName update
 * @apiGroup 部门管理
 *
 * @apiParam {int}     id 角色id【必填】
 * @apiParam {String}  name 部门名称【必填】
 * @apiParam {int}     pid 父级部门id【必填】
 * @apiParam {String}  address 地址【必填】
 * @apiParam {String}  phone 电话【必填】
 * @apiParam {int}     sort_num 排序【必填】
 * @apiParam {int}     status 部门状态 (0:正常 1:停用)【必填】
 *
 * @apiUse RequestHeader
 * @apiUse updateSuccess
 * @apiUse RequestError
 */
async function updateAction(ctx: Context, next: Next) {
    const { id = '', name = '', pid = '', address = '', phone = '', sort_num = '', status = '' } = ctx.request.body;
    try {
        await knex('sys_org').where({ id: id }).update({
            name,
            pid,
            address,
            phone,
            sort_num,
            status,
        });
        ctx.success('', '修改成功');
    } catch (e) {
        ctx.fail(500, '修改失败  ' + e);
    }
    return next();
}

/**
 * @api {delete} /org/delete 删除部门
 * @apiVersion 1.0.0
 * @apiDescription create by wuyanshen
 * @apiName delete
 * @apiGroup 部门管理
 *
 * @apiParam {int} id 部门id【必填】
 *
 * @apiUse RequestHeader
 * @apiUse deleteSuccess
 * @apiUse RequestError
 */
async function deleteAction(ctx: Context, next: Next) {
    const { id } = ctx.query;
    try {
        const res = await knex('sys_org').where({ pid: id }).select();
        if (res && Array.isArray(res) && res.length > 0) {
            ctx.fail(402, '存在子部门不允许删除');
            return next();
        }
        await knex('sys_org').where({ id: id }).delete();
        ctx.success('', '删除成功');
    } catch (e) {
        ctx.fail(500, '删除失败  ' + e);
    }
    return next();
}

const orgController = {
    retrieveAction,
    addAction,
    updateAction,
    deleteAction,
    treeAction,
    treeScopeAction,
};

export default orgController;
